package com.enjoy.netty.basic.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 9999;
        EchoServer echoServer = new EchoServer(port);
        System.out.println("服务器启动");
        echoServer.start();
        System.out.println("服务器关闭");
    }

    public void start() throws InterruptedException {
        final EchoServerHandler echoServerHandler = new EchoServerHandler();
        /*线程组*/
        EventLoopGroup group = new NioEventLoopGroup();
        /*服务端启动必备*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(group).channel(NioServerSocketChannel.class)//nio的通信模式
                    .localAddress(new InetSocketAddress(this.port))//指定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            //添加换行解码器
                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            socketChannel.pipeline().addLast(echoServerHandler);
                        }
                    });
            final ChannelFuture future = bootstrap.bind().sync();//异步绑定到服务器,sync()会阻塞到完成
            future.channel().closeFuture().sync();//阻塞当前线程,直到服务器的channel被关闭
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
